<?php
namespace apps\admin\controller;
use apps\common\controller\Backend;


class Roles extends Backend
{
	/**
	 * 角色列表
	 */
    public function index()
    {
        if(is_ajax()){
			$where = [];
			$name = input('title');
			if(!empty($name)) $where['title'] = ['like','%'.$name.'%'];

			$lists = db('admin_role')->where($where)->order("role_id","desc")->select();  
			foreach($lists as $k=>$v){
				$lists[$k]['create_time']=date('Y-m-d H:i:s',$v['create_time']);
				$lists[$k]['update_time']=date('Y-m-d H:i:s',$v['update_time']);
			} 
            return json(['code'=>0, 'msg'=>'success', 'data'=>$lists]);
        }        
	    $role = db('admin_role')->where(['status'=>1])->order("role_id","asc")->select();
	    return $this->fetch('index',['roles'=>$role]);
    }
	
	/**
	 * 编辑角色
	 */
	public function edit(){
		if(is_ajax()){
			$user = db('admin_role')->where(['role_id'=>input('role_id')])->find();  			   
            return $this->renderSuccess($user,'保存成功');
		}		 
		$user = db('admin')->where(['user_id'=>input('user_id')])->find();  
		$role = db('admin_role')->where(['status'=>1])->select();
		return $this->fetch('edit',[ 'admin'=>$user, 'roles'=>$role ]);
	}
	
	/**
	 * 添加角色
	 */
	public function add(){
	    if(is_ajax()){
	        $exits = db('admin_role')->where(['title'=>input('title')])->find();
	        if($exits){
	            return $this->renderError('该名称已经存在；请更换');
	        }
	        $data = [
	            'title' => input('title'),
	            'create_time' => time(),
				'update_time' => time(),
	            'status' => input('status')=='on'?1:0,
	        ];
	        $ret = db('admin_role')->insert($data);
	        if($ret){
	            return $this->renderSuccess([],'保存成功');
	        }
	        return $this->renderError('保存失败');
	    }
	    return $this->fetch('add');
	}

	/**
	 * 删除角色
	 */
	public function del(){
		if(is_ajax()){			
			$id = input('id');
			$exits = db('admin_role')->where("role_id IN ({$id})")->delete();
			if($exits){
				return $this->renderSuccess([],'删除成功');
			}
			return $this->renderError('删除失败');
		}
	}
	
}
